<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="180px">
      <el-form-item prop="deviceSn">
        <el-input
          v-model="queryParams.deviceSn"
          placeholder="设备ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="deviceType">
        <el-input
          v-model="queryParams.deviceType"
          placeholder="设备类型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="deviceSource">
        <el-select v-model="queryParams.deviceSource" placeholder="设备源">
            <el-option
                v-for="dict in deviceSourceOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="specModel">
        <el-select v-model="queryParams.specModel" placeholder="设备型号">
            <el-option
                v-for="dict in deviceModelOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="manufacturer">
        <el-select v-model="queryParams.manufacturer" placeholder="厂商">
            <el-option
                v-for="dict in supplierOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始更新时间"
          end-placeholder="结束更新时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['buz:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buz:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['buz:device:edit']"
        >编辑</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['buz:device:edit']"
        >查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['buz:device:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceSn"  width="120px" />
      <el-table-column label="设备名称" align="center" prop="deviceName"  width="120px"/>
      <el-table-column label="设备型号" align="center" prop="specModel"  width="120px"/>
      <el-table-column label="IMEI" align="center" prop="imei"  width="120px"/>
      <el-table-column label="设备类型" align="center" prop="deviceType"  width="120px"/>
      <el-table-column label="设备源" align="center" prop="deviceSource">
        <template scope="scope">
            <span v-if="scope.row.deviceSource === 0">家庭设备</span>
            <span v-else-if="scope.row.deviceSource === 1">机电设备</span>
        </template>
      </el-table-column>
      <el-table-column label="设备点位" align="center" prop="pointLocation"  width="180px"/>
        
      <el-table-column label="设备分类" align="center" prop="deviceCategory"  width="120px">
        <template scope="scope">
            <span v-if="scope.row.deviceCategory === 1">网关</span>
            <span v-else-if="scope.row.deviceCategory === 2">网关子设备</span>
            <span v-else-if="scope.row.deviceCategory === 3">wifi</span>
        </template>
      </el-table-column>
      <el-table-column label="设备厂商" align="center" prop="manufacturer" />
      <el-table-column label="在线状态" align="center" prop="deviceOnline">
        <template scope="scope">
            <span v-if="scope.row.deviceOnline === 0">离线</span>
            <span v-else-if="scope.row.deviceOnline === 1">在线</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="160px">
          <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['buz:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buz:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="deviceSn">
              <el-input v-model="form.deviceSn" placeholder="设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备点位" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备大类" prop="deviceBaseId">
              <el-select v-model="form.deviceBaseId" placeholder="设备类型">
                <el-option
                    v-for="dict in deviceTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice,listDeviceType } from "@/api/buz/device";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Device",
  components: { Treeselect },
  data() {
    return {
      // 部门树选项
      deptOptions: undefined,
      //设备在线状态数据
      deviceOnlineOptions:[],
      //设备分类数据
      deviceClassifyOptions:[],
      //设备类型数据
      deviceTypeOptions:[],
      //厂商数据
      supplierOptions:[],
      //设备型号数据
      deviceModelOptions:[],
      //设备源数据
      deviceSourceOptions: [],
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceSn: null,
        deviceName: null,
        deviceType: null,
        deptId: null,
        roomNum: null,
        groupId: null,
        deviceSource: null,
        deviceCategory: null,
        brand: null,
        specModel: null,
        manufacturer: null,
        manufacturerNo: null,
        supplier: null,
        productTime: null,
        maintainStarttime: null,
        maintainEndtime: null,
        deviceDescription: null,
        imei: null,
        deviceOnline: null,
        ontimeData: null,
        deviceStatus: null,
        regionName: null,
        bimNo: null,
        longitude: null,
        latitude: null,
        purchaseTime: null,
        purchasePrice: null,
        maintainCompany: null,
        regionId: null,
        buildingId: null,
        floor: null,
        subSystemType: null
      },
      // 表单参数
      form: {},
      //选中表格数据
      rows:{},
      // 表单校验
      rules: {
        deviceSn: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "设备点位不能为空", trigger: "blur" }
        ],
        deviceBaseId: [
          { required: true, message: "设备大类不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("supplier_device_buz").then(response => {
      this.supplierOptions = response.data;
    });
    this.getDicts("model_device_buz").then(response => {
      this.deviceModelOptions = response.data;
    });
    this.getDicts("source_device_buz").then(response => {
      this.deviceSourceOptions = response.data;
    });
    this.getDicts("online_device_buz").then(response => {
      this.deviceOnlineOptions = response.data;
    });
    this.getDicts("classify_device_buz").then(response => {
      this.deviceClassifyOptions = response.data;
    });
    // this.getDicts("type_device_buz").then(response => {
    //   this.deviceTypeOptions = response.data;
    // });
  },
  methods: {
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceSn: null,
        deviceBaseId: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange=[];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceSn)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
      //获取设备大类数据
      this.getDeviceType();
      //获取设备点位数据
      this.getTreeselect();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceSn || this.ids;
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addDevice(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceSn || this.ids;
      this.$confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDevice(deviceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buz/device/export', {
        ...this.queryParams
      }, `buz_device.xlsx`)
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getDeviceType(){
      listDeviceType().then(response => {
        // this.deviceList = response.rows;
        
        for (let index = 0; index < response.rows.length; index++) {
          const obj = {};
          const element = response.rows[index];
          obj.value = element.id;
          obj.label = element.baseType+'('+ element.specModel +')';
          this.deviceTypeOptions.push(obj);
        }
      });
    }
  }
};
</script>